package com.sy.simpleegg.ui.fragment

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.lifecycle.lifecycleScope
import com.sy.simpleegg.R
import com.sy.simpleegg.base.BaseMvpFragment
import com.sy.simpleegg.constant.Constant
import com.sy.simpleegg.databinding.FragmentTextBinding
import com.sy.simpleegg.ext.logFile
import com.sy.simpleegg.ext.onClick
import com.sy.simpleegg.ext.showToastMsg
import com.sy.simpleegg.mvp.contract.PackageManageContract
import com.sy.simpleegg.mvp.presenter.PackageManagePresenter
import com.sy.simpleegg.ui.layout.TouchLinearLayout
import com.sy.simpleegg.util.Preference

class TextFragment :
    BaseMvpFragment<PackageManageContract.View, PackageManageContract.Presenter, FragmentTextBinding>(),
    PackageManageContract.View {

    /**
     * 首页说明内容
     */
    private var instructions: String by Preference(Constant.SETTING_HOME_INSTRUCTIONS, "")

    companion object {
        fun getInstance(): TextFragment = TextFragment()
    }

    override fun createPresenter(): PackageManageContract.Presenter = PackageManagePresenter(lifecycleScope)

    override fun attachLayoutRes(): Int = R.layout.fragment_config

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

    }

    override fun initView(view: View) {
        super.initView(view)

        binding.etInstructions.setText(instructions)

        binding.btnSave.onClick {
            saveInstructions()
        }

        binding.rlTouch.setTouchListener(object : TouchLinearLayout.TouchListener {
            override fun touch() {
                startCountDown()
            }
        })
    }

    override fun getViewBinding(
        inflater: LayoutInflater,
        container: ViewGroup?,
    ): FragmentTextBinding {
        return FragmentTextBinding.inflate(inflater, container, false)
    }

    override fun lazyLoad() {

    }

    override fun onResume() {
        super.onResume()
        logFile("${javaClass.simpleName} onResume")
    }

    override fun onHiddenChanged(hidden: Boolean) {
        super.onHiddenChanged(hidden)
        if (hidden) {
            logFile("${javaClass.simpleName}隐藏")
        } else {
            logFile("${javaClass.simpleName}显示")
        }
    }


    override fun showLoading() {

    }

    override fun hideLoading() {

    }

    /**
     * 保存说明内容
     */
    private fun saveInstructions(){
        try {
            val etInstructions = binding.etInstructions.text.toString()
            if (etInstructions.isEmpty()){
                showToastMsg(requireContext().getString(R.string.instructions_null))
                return
            }
            instructions = etInstructions
            showToastMsg(requireContext().getString(R.string.save_success))
        }catch (e: Exception){
            e.printStackTrace()
            logFile("保存说明内容失败：${e.message}")
        }
    }
}